const express = require('express');
const session = require('express-session');
const app = express();
const path = require('path');
const todoListModel = require('./db/model/todoListModel');
// 支持post数据
app.use(express.urlencoded({extended:false}));
// 支持session
app.use(session({
    secret: 'atguigu', 
    saveUninitialized: false,
    resave: false ,
    cookie:{
        maxAge:1000 * 60 * 60 * 24 * 15
    }
}));
// 支持ejs
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');

// 设置静态资源
app.use(express.static(path.resolve(__dirname, './public')));

app.get('/index', (req, res)=>{
    let {page} = req.query;// 获取当前页
    const pageSize = 2;
    todoListModel.count({}).then(total=>{
        // 获取总条数 total，根据总条数和每页显示几条，计算出总页数
        let totalPage = Math.ceil(total/pageSize);
        let skipNum = (page - 1) * pageSize; // 计算出当前页应该跳过几条
        // 根据跳过的条数和每页显示几条，获取当前页的列表数据
        todoListModel.find({}).skip(skipNum).limit(pageSize).sort({_id:-1}).then(todoList=>{
            console.log(todoList.length);
            // console.log('todoList: ', todoList);
            // 将当前页列表数据，总页码，当前页 分配到模板中使用
            res.render('index', {todoList, totalPage, page:+page});
        })
    })
    
    
})

app.post('/addTodo', (req,res)=>{
    let {title} = req.body;
    todoListModel.create({title}).then(todo=>{
        // 添加成功后重定向到index路由，获取最新的列表数据并渲染
        res.redirect('/index');
    })
})

// 根据id删除数据
app.get('/delete', (req, res)=>{
    // query参数
    let {_id} = req.query;
    todoListModel.deleteOne({_id}).then(data=>{
        res.redirect('/index');
    })
})
// params 参数 path参数  必须要有占位符
app.get('/delete/:_id', (req, res)=>{
    let {_id} = req.params;
    todoListModel.deleteOne({_id}).then(data=>{
        res.redirect('/index');
    })
})

app.listen(8080, ()=>{
    console.log('server run at 8080');
})